import React, { useContext, useMemo } from 'react';
import { Card, Button, message, Space } from 'antd';
import { history } from 'umi';
import '../common/style.less';
import { NeedUpdateContext } from '../common/NeedContext';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import pageStyles from '@/common/pageLayout.less';
import { getKeyRouter, getPosIDs, getTenantID, getUserID } from '@/utils';
import { BZZ_CHECKSTATE, SHTH_CHECKSTATE, closeCurrent } from '../../Acommon';
import { WorkflowHndTaskBtn } from '@/components/WorkflowCommonCopy';
import { NeedUpdateAPI } from '../common/type';
import {
  BMSH_STATE,
  FGLDSH_STATE,
  KCBSH_STATE,
  JHXD_STATE,
  JZLZ_STATE,
  XQBZ_STATE,
  XQZF_STATE,
  ZRBGH_STATE,
  purchaseNeedCategory,
  purchaseNeedController,
  SHZ_STATE,
  isMomentAddFun,
  isMomentSubmitFun,
} from '../common/Format';
import { ILoadMapTypeAll } from '@/common';

/**
 * @UpdateNeedCardBaseInfo 需求详情容器组件
 * @param onSubmit 底部按钮提交事件
 * @param onCancel 底部按钮取消需求事件
 * @param openDrawer 底部审批记录事件 //TODO: 梁豪杰 后续审批记录按钮移到 左上角操作按钮 组件内部
 * @param openModal 打开物料选择弹窗
 * @param children 子组件内容
 * @param curRes 权限对象
 * @returns
 */

/**
 * 新增编辑页-卡片包裹层-主要做卡片Title-底部button按钮
 * */
const UpdateNeedCardBaseInfo: React.FC<NeedUpdateAPI.IUpdateNeedCardBaseInfo> = ({ onSubmit, onCancel, onExport, openModal, curRes, children }) => {
  /**解构:需求详情 随机id*/
  const { isView, needInfo, pageRouterDomID, nodesFlowListMemo, materialList, reloadInfoFunc, locationState } = useContext(NeedUpdateContext);

  /**根据状态设置标题*/
  const title = useMemo(() => {
    switch (needInfo?.state) {
      case XQBZ_STATE():
        return '计划编制';
      // case BMSH_STATE():
      //   return '部门审核';
      // case KCBSH_STATE():
      //   return '科创部专责复核';
      // case FGLDSH_STATE():
      //   return '编制中';
      // case JZLZ_STATE():
      //   return '集中论证';
      // case ZRBGH_STATE():
      //   return '主任办公会审议';
      case JHXD_STATE():
        return '计划下达';
      case XQZF_STATE():
        return '已作废';
      case SHZ_STATE():
        return '审核中';
      default:
        return '计划编制';
    }
  }, [needInfo?.state]);

  /**提交时暂存文件*/
  const clickBeforeFun = () => {
    return new Promise((resolve) => {
      // 获取当前的状态 是集中论证
      if (needInfo?.state == JZLZ_STATE() && needInfo?.checkState == BZZ_CHECKSTATE() && curRes?.['/purchaseNeedController/edit']) {
        /** 校验论证意见是否上传 */
        for (let i = 0; i < materialList?.length; i++) {
          if (materialList[i]?.needProofFlag && materialList[i]?.needProofFlag == 1) {
            if (!materialList[i]?.needProofURL) {
              message.warn(`提示：${materialList[i]?.fullName || '--'}，缺少需求论证意见！`);
              return;
            }
          }

          if (materialList[i]?.needImportFlag && materialList[i]?.needImportFlag == 1) {
            if (!materialList[i]?.needImportURL) {
              message.warn(`提示：${materialList[i]?.fullName || '--'}，缺少进口专业人员论证意见！`);
              return;
            }
          }

          if (materialList[i]?.needSingleFlag && materialList[i]?.needSingleFlag == 1) {
            if (!materialList[i]?.needSingleURL) {
              message.warn(`提示：${materialList[i]?.fullName || '--'}，缺少单一来源论证意见！`);
              return;
            }
          }
        }
        resolve(onSubmit('暂存'));
      } else {
        resolve(null);
      }
    });
  };

  const btnMemo = (flag = false) => {
    return (
      <>
        {
          // 新增
          ((typeof needInfo?.state == 'undefined' && curRes?.['/purchaseNeedController/add']) ||
            // 编辑
            (needInfo?.state && curRes?.['/purchaseNeedController/edit'] && needInfo?.state == XQBZ_STATE() && !needInfo?.checkState && !isView) ||
            // 集中论证
            (needInfo?.state == JZLZ_STATE() && needInfo?.checkState == BZZ_CHECKSTATE() && nodesFlowListMemo) ||
            // 审核退回起草人
            (needInfo?.state == SHZ_STATE() &&
              needInfo?.checkState == SHTH_CHECKSTATE() &&
              needInfo?.paramObject &&
              needInfo?.ownerID == getUserID() &&
              needInfo?.ownPositionID == getPosIDs() &&
              !isView)) &&
            flag &&
            isMomentAddFun() && (
              <Button
                type="primary"
                onClick={() => {
                  if (needInfo?.state == JZLZ_STATE() && needInfo?.checkState == BZZ_CHECKSTATE()) {
                    /** 校验论证意见是否上传 */
                    for (let i = 0; i < materialList?.length; i++) {
                      if (materialList[i]?.needProofFlag && materialList[i]?.needProofFlag == 1) {
                        if (!materialList[i]?.needProofURL) {
                          message.warn(`提示：${materialList[i]?.fullName || '--'}，缺少需求论证意见！`);
                          return;
                        }
                      }

                      if (materialList[i]?.needImportFlag && materialList[i]?.needImportFlag == 1) {
                        if (!materialList[i]?.needImportURL) {
                          message.warn(`提示：${materialList[i]?.fullName || '--'}，缺少进口专业人员论证意见！`);
                          return;
                        }
                      }

                      if (materialList[i]?.needSingleFlag && materialList[i]?.needSingleFlag == 1) {
                        if (!materialList[i]?.needSingleURL) {
                          message.warn(`提示：${materialList[i]?.fullName || '--'}，缺少单一来源论证意见！`);
                          return;
                        }
                      }
                    }
                  }
                  onSubmit('暂存');
                }}
              >
                暂存
              </Button>
            )
        }
        {isMomentSubmitFun() &&
          curRes?.['/purchaseNeedController/startProcess/{starterDeptID}'] &&
          curRes?.['/purchaseNeedController/edit'] &&
          (typeof needInfo?.state == 'undefined' || (needInfo?.state && needInfo?.state == XQBZ_STATE() && !needInfo?.checkState)) && (
            <Button type="primary" onClick={() => onSubmit('暂存', true)}>
              提交
            </Button>
          )}

        {locationState?.returnPathName && (
          <Button danger onClick={() => closeCurrent(locationState?.returnPathName)}>
            关闭
          </Button>
        )}

        {/* {curRes['/purchaseNeedController/invalid'] &&
          needInfo?.id &&
          needInfo?.applyerID == getUserID() &&
          needInfo?.applyPositionID == getPosIDs() &&
          (needInfo?.state == SHZ_STATE() || needInfo?.state == JZLZ_STATE() || needInfo?.state == ZRBGH_STATE()) && (
            <Button
              type="primary"
              danger
              // icon={<RollbackOutlined />}
              onClick={() => {
                onCancel(true);
              }}
            >
              撤销
            </Button>
          )} */}
      </>
    );
  };

  return (
    <div
      id={pageRouterDomID}
      className="needUpdateView-imageBox"
      style={{
        position: 'relative',
        overflow: 'hidden',
        height: '100%',
        width: '100%',
      }}
    >
      <Card
        title={'计划状态：' + title}
        className={pageStyles['page-view-cardView']}
        bodyStyle={{
          padding: '0px 10px',
          display: 'flex',
          flexDirection: 'column',
        }}
        extra={
          <Space>
            {needInfo?.id &&
              (needInfo?.state == JZLZ_STATE() || needInfo?.state == ZRBGH_STATE() || needInfo?.state == JHXD_STATE() || needInfo?.state == XQZF_STATE()) &&
              curRes?.['/purchaseNeedController/export'] && (
                <Button
                  type={'primary'}
                  // size={'small'}
                  // icon={<ExportOutlined />}
                  // className="manageBtntTxtStyle"
                  onClick={onExport}
                >
                  导出
                </Button>
              )}
            {btnMemo(true)}
            <WorkflowHndTaskBtn
              flowDetailInfo={needInfo}
              requestController={purchaseNeedController}
              reloadCallback={reloadInfoFunc}
              isAloneSubmit={
                (needInfo?.state == JZLZ_STATE() && needInfo?.checkState == BZZ_CHECKSTATE()) ||
                (needInfo?.state == FGLDSH_STATE() && needInfo?.checkState == SHTH_CHECKSTATE())
              }
              clickBeforeFun={clickBeforeFun}
              flowBusinessType={purchaseNeedCategory()}
              applyHeader={'apply'}
              revokeRequestUrl={'/purchaseNeedController/invalid'}
              revokeRequestState={`${getTenantID()}${ILoadMapTypeAll.NEED_STATE}`}
              isShowRevokeStateList={[SHZ_STATE(), JZLZ_STATE(), ZRBGH_STATE()]}
              revokeTitle={needInfo?.needName}
              revokeSuccessCallback={() => {
                history.push({
                  // 新增编辑页
                  pathname: `/purchaseNeedController/edit/:${getKeyRouter()}${getKeyRouter()}`,
                  state: {
                    info: needInfo,
                    isView: false,
                    delRouterName: history.location.pathname,
                  },
                });
              }}
            />
          </Space>
        }
        tabBarExtraContent={<div>你好</div>}
      >
        <ScrollBarLayout>
          <div className={pageStyles['fromView-stylesPage']}>{children}</div>
        </ScrollBarLayout>

        <div className={'baseinfo-footer'}>
          <Space>{btnMemo()}</Space>
        </div>
      </Card>
    </div>
  );
};

export default UpdateNeedCardBaseInfo;
